package com.junxonline.instant.terminal.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.junxonline.instant.common.constant.RedisMqChannelConstant;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 刷新终端状态消费者
 *
 * @author JunX
 * @date 2021-11-10
 */
@Log4j2
@Component
public class TerminalStatusListener implements MessageListener {

    @Autowired
    private TerminalMapper terminalMapper;

    /**
     * 消息处理
     *
     * @param message 消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        String msg = (String) serializer.deserialize(message.getBody());
        log.info("收到频道[" + RedisMqChannelConstant.KEY_REDIS_MSG_CHANNEL_TERMINAL_STATUS + "]消息 => {}", msg);
        HashMap<String, Object> data = JSON.parseObject(msg, new TypeToken<HashMap<String, Object>>(){}.getType());
        if (data != null) {
            String terminalCode = (String) data.get("terminalCode");
            Integer status = (Integer) data.get("status");
            // 刷新终端状态
            if (StrUtil.isNotBlank(terminalCode) && status != null) {
                terminalMapper.updateStatusAndHeartBeatTimeByCode(status, DateUtil.date(), terminalCode);
                log.info("刷新终端[" + terminalCode + "]的播放状态为 -> {}", status);
            }
        }

    }

}
